package dnablockfinder;

public final class Analysis {
	private char majorityAmino;
	private double percentMatch;
	private Analysis previous;
	private Analysis next;
	private double filteredValue;
	private double leftDiff;
	private double rightDiff;
	private double totDiff;

	public Analysis(char majorityAmino) {
		this.majorityAmino = majorityAmino;
		this.percentMatch = 1;
		this.filteredValue = 1;
	}

	public Analysis(Analysis prevData, Analysis leftData, double leftLength,
			Analysis rightData, double rightLength) {
		majorityAmino = leftData.majorityAmino;
		percentMatch = leftData.percentMatch * rightLength
			/ (leftLength + rightLength);
		double rightPercent = rightData.percentMatch * leftLength
			/ (leftLength + rightLength);
		if (majorityAmino == rightData.majorityAmino)
			percentMatch += rightPercent;
		else if (rightPercent > percentMatch) {
			majorityAmino = rightData.majorityAmino;
			percentMatch = rightPercent;
		}

		previous = prevData == null ? this
			: (prevData.shouldIgnore() ? prevData.previous : prevData);
		next = this;
		previous.next = this;

		filteredValue = 0;
		leftDiff = 0;
		rightDiff = 0;
		totDiff = -2;
	}

	public void filter(int filterRadius,
			Analysis leftData, Analysis rightData) {
		filteredValue = percentMatch * (filterRadius + 1);
		Analysis crrntPrev = previous, crrntNext = next;
		for (int i = filterRadius; i > 0; i --) {
			filteredValue += (crrntPrev.percentMatch + crrntNext.percentMatch)
				* (1 + (filterRadius - Math.abs(i)));
			crrntPrev = crrntPrev.previous;
			crrntNext = crrntNext.next;
		}
		filteredValue /= Math.pow(filterRadius + 1, 2);

		if (! leftData.shouldIgnore() && ! rightData.shouldIgnore()) {
			leftDiff = filteredValue - leftData.filteredValue;
			rightDiff = filteredValue - rightData.filteredValue;
			totDiff = leftData.filteredValue - rightData.filteredValue;
		}
	}

	public String print() {
		return totDiff == -2 ? "" : "" + majorityAmino + "," + percentMatch
			+ "," + filteredValue
			+ "," + leftDiff + "," + rightDiff + "," + totDiff;
	}
	
	public boolean shouldIgnore() {
		return majorityAmino == '-' && percentMatch > .5;
	}
}
